package com.example.dish.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.admin_api.EmployeeClient;
import com.example.admin_model.dto.EmployeeDTO;
import com.example.dish.mapper.CategoryMapper;
import com.example.dish.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dish.service.DishService;
import com.example.dish.service.SetmealService;
import com.example.dish_model.entity.Category;
import com.example.dish_model.entity.Dish;
import com.example.dish_model.entity.Setmeal;
import com.example.exceptions.BusinessException;
import com.example.exceptions.enumetation.ResponseEnum;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 菜品及套餐分类 服务实现类
 * </p>
 *
 * @author sjz
 * @since 2024-06-30
 */
@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {


    @Resource
    private HttpServletRequest request;

    @Resource
    @Lazy
    private SetmealService setmealService;

    @Resource
    @Lazy
    private DishService dishService;

    @Resource
    private EmployeeClient employeeClient;


    @Override
    public void removeCategory(String id) {
        log.info("id是什么:{}", id);
        //校验身份
        EmployeeDTO dto = new EmployeeDTO();
        String token = request.getHeader("Authorization").replace("\"", "");
        dto.setToken(token);
        employeeClient.validate(dto);
        //获取当前要删除的分类
        Category category = this.getById(id);
        log.info("获取删除对象:{}", category);
        Integer categoryType = category.getType();

        log.info("id:{}对印的类型:{}", id, categoryType);

        long count = 0;
        //1.要删的是菜品
        if (categoryType == 1) {
            //查询菜品表,看该分类是否已经关联菜品
            LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Dish::getCategoryId, id);
            count = dishService.count(wrapper);
        }
        //2.要删的是套餐
        if (categoryType == 2) {
            //查询套餐表,看该分类是否已经关联套餐
            LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Setmeal::getCategoryId, id);
            count = setmealService.count(wrapper);
        }

        if (count > 0) {
            //已经关联套餐,抛出业务异常
            throw new BusinessException(ResponseEnum.CATEGORY_DELETE_FAIL);
        }
        //正常删除分类
        removeById(id);
    }

}
